package com.paradoxie.autoscrolltextview;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;

/**
 * 自定义view
 */
public class VerticalTextview extends DependentLayout {

    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.DEBUG, 0x00201, "MY_TAG");

    private static final int FLAG_START_AUTO_SCROLL = 0;
    private static final int FLAG_STOP_AUTO_SCROLL = 1;

    private int mTextSize = 16;

    private OnItemClickListener itemClickListener;
    private Context mContext;
    private int currentId = 0;
    private int clickId = 0;
    private ArrayList<String> textList;
    private EventHandler handler;
    private Text t1,t2,t3;
    private long animDuration;
    private boolean isFirst = true;

    /**
     * VerticalTextview
     * @param context
     * @param attrSet
     */
    public VerticalTextview(Context context, AttrSet attrSet) {
        super(context, attrSet);
        mContext = context;
        textList = new ArrayList<String>();

        makeView();
    }

    /**
     * setText
     * @param textSize
     * @param padding
     */
    public void setText(int textSize, int padding){
        this.setText(textSize,padding,0);
    }

    /**
     * setText
     * @param textSize
     * @param padding
     * @param textColor
     */
    public void setText(int textSize, int padding, int textColor){
        setText(textSize,padding,padding,padding,padding,textColor);
    }

    /**
     * setText
     * @param textSize
     * @param left
     * @param top
     * @param right
     * @param bottom
     * @param textColor
     */
    public void setText(int textSize, int left, int top, int right, int bottom, int textColor) {
        mTextSize = textSize;

        if(textColor!=0){
            t1.setTextColor(new Color(textColor));
            t2.setTextColor(new Color(textColor));
            t3.setTextColor(new Color(textColor));
        }

        t1.setTextSize(textSize);
        t2.setTextSize(textSize);
        t3.setTextSize(textSize);

        t1.setPadding(left,top,right,bottom);
        t2.setPadding(left,top,right,bottom);
        t3.setPadding(left,top,right,bottom);

        setBindStateChangedListener(new BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                t3.setWidth(getWidth());
                t3.setHeight(getHeight());
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {
                if(handler!=null){
                    handler.removeAllEvent();
                }
            }
        });
    }

    /**
     * setAnimTime
     * @param animDuration
     */
    public void setAnimTime(long animDuration) {
        this.animDuration = animDuration;
    }

    /**
     * set time.
     *
     * @param time
     */
    public void setTextStillTime(final long time) {
        EventRunner runner = EventRunner.create(true);// create()的参数是 true时，则为托管模式
        // 需要对 EventRunner 的实例进行校验，因为创建 EventRunner 可能失败，如创建线程失败时，创建 EventRunner 失败。
        if (runner == null) {
            return;
        }
        handler = new EventHandler(runner){
            // 重写实现processEvent方法
            @Override
            public void processEvent(InnerEvent event) {
                super.processEvent(event);
                if (event == null) {
                    return;
                }
                int eventId = event.eventId;
                switch (eventId) {
                    case FLAG_START_AUTO_SCROLL:
                        // 待执行的操作，由开发者定义
                        if (textList.size() > 0) {

                           runUI(new Runnable() {
                                @Override
                                public void run() {

                                    clickId++;
                                    if(clickId==textList.size()){
                                        clickId =0;
                                    }

                                    t1.setWidth(getWidth());
                                    t1.setHeight(getHeight());
                                    t2.setWidth(getWidth());
                                    t2.setHeight(getHeight());

                                    int height2 = t1.getHeight();
                                    AnimatorProperty out = createAnimatorProperty();
                                    out.moveFromY(0).moveToY(-height2).setDuration(animDuration);
                                    out.setTarget(t1);
                                    out.start();

                                    int height = t2.getHeight();
                                    AnimatorProperty out2 = createAnimatorProperty();
                                    out2.moveFromY(height).moveToY(0).setDuration(animDuration);
                                    out2.setTarget(t2);
                                    out2.setStateChangedListener(new Animator.StateChangedListener() {
                                        @Override
                                        public void onStart(Animator animator) {
                                            if(t1.getVisibility() != VISIBLE){
                                                t1.setVisibility(VISIBLE);
                                            }
                                            if(t2.getVisibility() != VISIBLE){
                                                t2.setVisibility(VISIBLE);
                                            }


                                            handler.postTask(new Runnable() {
                                                @Override
                                                public void run() {
                                                    mContext.getUITaskDispatcher().asyncDispatch(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            t3.setVisibility(INVISIBLE);
                                                        }
                                                    });
                                                }
                                            }, 60);
                                        }

                                        @Override
                                        public void onStop(Animator animator) {

                                        }

                                        @Override
                                        public void onCancel(Animator animator) {

                                        }

                                        @Override
                                        public void onEnd(Animator animator) {
                                            mContext.getUITaskDispatcher().asyncDispatch(new Runnable() {
                                                @Override
                                                public void run() {
                                                    t3.setText(textList.get(currentId));
                                                    t3.setVisibility(VISIBLE);

                                                    t1.setVisibility(INVISIBLE);
                                                    t2.setVisibility(INVISIBLE);

                                                    t1.setText(textList.get(currentId));

                                                    if(currentId==textList.size()-1){
                                                        t2.setText(textList.get(0));
                                                    }else{
                                                        t2.setText(textList.get(currentId+1));
                                                    }

                                                    clickId = currentId;
                                                    currentId++;
                                                    if(currentId==textList.size()){
                                                        currentId =0;
                                                    }
                                                }
                                            });

                                        }

                                        @Override
                                        public void onPause(Animator animator) {

                                        }

                                        @Override
                                        public void onResume(Animator animator) {

                                        }
                                    });
                                    out2.start();
                                }
                            });
                            if(isFirst){
                                isFirst = false;
                                handler.sendEvent(FLAG_START_AUTO_SCROLL, time);
                            }else{
                                handler.sendEvent(FLAG_START_AUTO_SCROLL, animDuration+time);
                            }

                        }

                        break;
                    case FLAG_STOP_AUTO_SCROLL:
                        handler.removeAllEvent();
                        break;
                }
            }
        };

    }

    /**
     * set Data list.
     *
     * @param titles
     */
    public void setTextList(ArrayList<String> titles) {
        textList.clear();
        textList.addAll(titles);
        currentId = 0;
        if(TextUtils.isNotEmpty(textList) && textList.size()>0){
            t1.setText(textList.get(currentId));
            t3.setText(textList.get(currentId));

            if(textList.size()>1) {
                t2.setText(textList.get(currentId+1));
                currentId++;
            }
        }

    }

    /**
     * start auto scroll
     */
    public void startAutoScroll()
    {
        if(TextUtils.isNotEmpty(textList) && textList.size()>1){

            if(getHeight()!=0){
                t3.setWidth(getWidth());
                t3.setHeight(getHeight());
            }

            t1.setVisibility(INVISIBLE);
            t2.setVisibility(INVISIBLE);
            t3.setVisibility(VISIBLE);
            handler.sendEvent(FLAG_START_AUTO_SCROLL);
        }

    }

    /**
     * stop auto scroll
     */
    public void stopAutoScroll() {
        handler.sendEvent(FLAG_STOP_AUTO_SCROLL);
    }

    private void makeView() {

        t1 = new Text(mContext);
        DirectionalLayout.LayoutConfig layoutConfig = new DirectionalLayout.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_CONTENT,
                DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        layoutConfig.alignment = LayoutAlignment.VERTICAL_CENTER|LayoutAlignment.LEFT;
        t1.setLayoutConfig(layoutConfig);
        t1.setMaxTextLines(1);
        t1.setTruncationMode(Text.TruncationMode.ELLIPSIS_AT_END);
        t1.setTextSize(mTextSize);
        addComponent(t1);

        t2 = new Text(mContext);
        DirectionalLayout.LayoutConfig layoutConfig2 = new DirectionalLayout.LayoutConfig(
                DirectionalLayout.LayoutConfig.MATCH_CONTENT,
                DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        layoutConfig2.alignment = LayoutAlignment.VERTICAL_CENTER|LayoutAlignment.LEFT;
        t2.setTruncationMode(Text.TruncationMode.ELLIPSIS_AT_END);
        t2.setLayoutConfig(layoutConfig2);
        t2.setMaxTextLines(1);
        t2.setTextSize(mTextSize);
        addComponent(t2);

        t3 = new Text(mContext);
        DirectionalLayout.LayoutConfig layoutConfig3 = new DirectionalLayout.LayoutConfig(
                DirectionalLayout.LayoutConfig.MATCH_CONTENT,
                DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        layoutConfig3.alignment = LayoutAlignment.VERTICAL_CENTER|LayoutAlignment.LEFT;

        Element element = getBackgroundElement();
        if(element == null){
            ShapeElement element2 = new ShapeElement();
            element2.setRgbColor(new RgbColor(255, 255, 255));
            t3.setBackground(element2);
        }else{
            t3.setBackground(element);
        }
        t3.setTruncationMode(Text.TruncationMode.ELLIPSIS_AT_END);
        t3.setLayoutConfig(layoutConfig3);
        t3.setMaxTextLines(1);
        t3.setTextSize(mTextSize);
        addComponent(t3);

        this.setClickedListener(new ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (TextUtils.isNotEmpty(itemClickListener) && textList.size() > 0) {
                    itemClickListener.onItemClick(clickId );
                }
            }
        });
    }

    /**
     * 监听
     * @param itemClickListener
     */
    public void setOnItemClickListener(OnItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    /**
     * 监听接口
     */
    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    /**
     * runUI
     * @param runnable
     */
    private static void runUI(Runnable runnable){
        // 切换到主线程
        EventRunner runner = EventRunner.getMainEventRunner();
        EventHandler eventHandler = new EventHandler(runner);
        //切换任务
        eventHandler.postSyncTask(runnable);
    }

}
